# -*- coding: utf-8 -*-
# Purpose: Support file for the test cases
# Created: 11/18/2008
# Copyright (c) 2008,2009 by University College London
# Authors:
# Didrik Pinte <dpinte@dipole-consulting.com>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with HydroPlatform for details.

import logging
import os
import sys
import unittest

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker


def hydroplatform_dir():
    """Return the directory containing the hydroplatform package"""
    thisdir = os.path.dirname(__file__)
    return os.path.join(thisdir, os.pardir)

def resource_dir():
    return os.path.join(hydroplatform_dir(), "resources")

def add_hydroplatform_dir_to_path():
    """Insert the hydroplatform directory at the beginning of the python path.

    If it's already part of the path, remove later occurrences.
    """
    hptdir = hydroplatform_dir()
    while 1:
        try:
            sys.path.remove(hptdir)
        except ValueError:
            break
    sys.path.insert(0, hptdir)

def add_thuban_path():
    '''
    Add the necessary path to run Thuban's tests
    '''
    import thubaninit
    


def init_hydroplatform():
    '''
    Initialise everyting to make the test cases run fine
    '''
    add_hydroplatform_dir_to_path()
    add_thuban_path()
    import Thuban.UI
    Thuban.UI.install_wx_translation()

add_hydroplatform_dir_to_path()
add_thuban_path()
from hydroplatform.model import database as db
from samples import load_sample_network1
    
    
def get_dbsession():
    url = 'sqlite:///:memory:'
    engine = create_engine(url, echo=True)
    engine.echo = False
    #engine = create_engine('sqlite:////tmp/test.db', echo=True)
    #db.check_and_upgrade(url) --> can't use it on a sqlite memory 
    #                           as the url always creates a new db
    db.metadata.create_all(engine)
    Session = sessionmaker(bind=engine, autoflush=True, autocommit=False)
    return Session()    

def save_sample_to_file(filename='/tmp/test.db'):
    if os.path.exists(filename):
        os.remove(filename)
    engine = create_engine('sqlite:///%s' % filename, echo=True)
    db.metadata.create_all(engine)
    Session = sessionmaker(bind=engine, autoflush=True, autocommit=False)
    session = Session()  
    
    load_sample_network1(session)

class Context(object):
    '''
    Fake Context object to be used for testing class that does not have access 
    to Thuban's context
    '''
    
    def __init__(self):
        self.session = Session()

class Session(object):
    '''
    Fake Session object to be used for testing class that does not have access 
    to Thuban's context.session
    '''    
    def __init__(self):
        pass 